package com.algorithm.sort;

import com.alibaba.fastjson.JSON;

/**
 * @author: tzj
 * @create: 2022-10-10
 * 冒泡排序
 **/
public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = new int[]{2, 5, 1, 9, 6};
        bubbleSort(arr, arr.length);
        System.out.println(JSON.toJSONString(arr));
    }

    public static void bubbleSort(int[] arr, int n) {
        if (n <= 1) return;
        for (int i = 0; i < n; i++) {
            Boolean flag = false;
            for (int j = 0; j < n - i - 1; j++) {
                // 核心，两两比较，大的往后移动
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
            // 数组排好序后就推出循环
            if (!flag) {
                break;
            }
        }
    }
}
